package cn.itcast.netty.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.function.Consumer;

public class HelloServer {
    public static void main(String[] args) {
        //1. 启动器，负责组装netty组件，启动服务器
        new ServerBootstrap()
                // 2.创建一个EventLoop组，包括BossEventLoop(处理可连接事件),WorkEventLoop(处理读写事件)
                // EventLoop里包含selector+thread
                .group(new NioEventLoopGroup())
                // 3.选择服务器的ServerSocketChannel的实现
                .channel(NioServerSocketChannel.class)
                // 4.boss负责处理连接  worker(child)负责处理读写，决定了worker(childer)可以执行那些操作(handler)
                .childHandler(
                        // 5.初始化和客户端进行读写的通道(channel),负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override  //在连接建立后被调用
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                // 6.添加具体的handler
                                ch.pipeline().addLast(new StringDecoder());     //将ByteBuf 转为字符串
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){       //自定义handler
                                    @Override  //处理读事件
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        // 打印上一步转换好的字符串
                                        System.out.println(msg);
                                    }
                                });
                            }
                        }
                )
                // 7.绑定监听端口
                .bind(8080);
    }
}
